package com.yisu.expressway.onedollar.activity;

import java.util.Arrays;
import java.util.List;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.will.network.images.round.CircleImageView;
import com.yisu.expressway.R;
import com.yisu.expressway.onedollar.adapter.PicGridListAdapter;
import com.yisu.expressway.onedollar.model.OrderShowItem;
import com.yisu.expressway.onedollar.presenter.IOrderShowPresenter;
import com.yisu.expressway.onedollar.presenter.impl.OrderShowPresenterImp;
import com.yisu.expressway.onedollar.view.IOrderShowView;
import com.yisu.expressway.onedollar.widget.NoScrollGridView;
import com.yisu.expressway.onedollar.widget.TitleView;
import com.yisu.expressway.ui.recyclerview.BaseRvAdapter;
import com.yisu.expressway.ui.recyclerview.DividerListItemDecoration;
import com.yisu.expressway.ui.recyclerview.PagingRecyclerView;
import com.yisu.expressway.ui.refresh.SuperSwipeRefreshLayout;
import com.yisu.expressway.utils.StringUtil;
import com.yisu.expressway.utils.ToastUtil;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Kaven on 2016/12/15.
 * 赢家晒单列表
 */

public class OrderShowListActivity extends BasicActivity implements IOrderShowView,
        PagingRecyclerView.SampleActionListener, PicGridListAdapter.PicItemClickListener {
    private static final String EXTRA_KEY_GOODS_BARCODE = "extra_key_goods_barcode";
    @Bind(R.id.title_bar)
    protected TitleView mTitleView;
    @Bind(R.id.refreshLayout)
    protected SuperSwipeRefreshLayout mRefreshLayout;
    @Bind(R.id.rv_content)
    protected PagingRecyclerView mOrderShowListRv;
    @Bind(R.id.empty_des)
    protected TextView mEmptyDesTv;
    @Bind(R.id.empty_action)
    protected TextView mEmptyActionTv;
    @Bind(R.id.empty)
    View mEmptyView;
    private IOrderShowPresenter mPresenter;
    private long mGoodsBarcode;
    private ImageView carImage;
    private AnimationDrawable mAnimation;
    private boolean isFreshEnable;

    public static void launch(Context context, long recordId) {
        Intent intent = new Intent(context, OrderShowListActivity.class);
        intent.putExtra(EXTRA_KEY_GOODS_BARCODE, recordId);
        context.startActivity(intent);
    }

    @OnClick(R.id.empty_action)
    void onActionClick() {
        jump2MainPage();
    }

    @Override
    protected int getThemeId() {
        return R.style.OneDollarTheme;
    }

    @Override
    protected int getInflateLayoutId() {
        return R.layout.activity_onedollar_order_show;
    }

    @Override
    protected void initPresenter() {
        mPresenter = new OrderShowPresenterImp(this, this);
        mPresenter.init();
    }

    @Override
    protected void releasePresenter() {
        if (mPresenter != null) {
            mPresenter = null;
        }
    }

    @Override
    protected void getIntentData(Intent intent) {
        long longExtra = intent.getLongExtra(EXTRA_KEY_GOODS_BARCODE, -1);
        if (longExtra < 0) {
            finish();
            return;
        }
        mGoodsBarcode = longExtra;
    }

    @Override
    protected void getSavedBundleData(Bundle bundle) {

    }

    @Override
    protected void initViews() {
        initFreshLayout();
        DividerListItemDecoration mListDivider = new DividerListItemDecoration(this,
                LinearLayoutManager.VERTICAL, 0);
        mOrderShowListRv.init(mListDivider, new LinearLayoutManager(this), this, 20);
        mEmptyDesTv.setText(getString(R.string.one_dollar_order_show_empty));
        mEmptyActionTv.setText(getString(R.string.one_dollar_go_now));
    }

    @Override
    protected void bindEvents() {
        mTitleView.setOnTitleBarClickEvent(new TitleView.OnTitleBarClickEvent() {
            @Override
            public void onLeftClick(View view) {
                finish();
            }

            @Override
            public void onTitleClick(View view) {

            }

            @Override
            public void onRightClick(View view) {

            }
        });
    }

    @Override
    protected boolean isNeedLogin() {
        return false;
    }

    @Override
    protected void onLoginStateChange(boolean login) {

    }

    @Override
    public void showToast(String toastMsg) {
        if (StringUtil.isNullOrEmpty(toastMsg)) {
            return;
        }
        ToastUtil.displayLongToastMsg(this, toastMsg);
    }

    @Override
    public void showLoadingDlg() {
        showLoading();
    }

    @Override
    public void dismissLoadingDlg() {
        dismissLoading();
    }

    @Override
    public void refreshView() {
        if (mAnimation != null) {
            mRefreshLayout.setRefreshing(false);
            mAnimation.stop();
            carImage.setImageResource(R.color.colorTransparent);
        }

        List<OrderShowItem> orderShowList = mPresenter.getOrderShowList();
        if (orderShowList == null || orderShowList.isEmpty()) {
            mEmptyView.setVisibility(View.VISIBLE);
            mRefreshLayout.setVisibility(View.GONE);
            return;
        }
        mEmptyView.setVisibility(View.GONE);
        mRefreshLayout.setVisibility(View.VISIBLE);
        mOrderShowListRv.dataFetchDone(orderShowList);
    }

    @Override
    public void jump2OrderShowDetailPage(long recordId) {
        if (recordId <= 0) {
            return;
        }
        OrderShowDetailActivity.launch(this, recordId);
    }

    @Override
    public void jump2OriginalPicPage(String picUrl) {
        if (TextUtils.isEmpty(picUrl)) {
            return;
        }
        DetailActivity.launch(this, picUrl, DetailActivity.TYPE_URL, "");
    }

    @Override
    public void jump2MainPage() {
        finish();
        startTargetActivity(OneDollarMainActivity.class);
    }

    private void initFreshLayout() {
        mRefreshLayout.setHeaderViewBackgroundColor(0xffefeff4);
        mRefreshLayout.setHeaderView(createHeaderView());
        mRefreshLayout.setTargetScrollWithLayout(true);
        mRefreshLayout
                .setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {

                    @Override
                    public void onRefresh() {
                        if (mAnimation != null) {
                            mAnimation.start();
                        }

                        mOrderShowListRv.refreshData();
                    }

                    @Override
                    public void onPullDistance(int distance) {
                        int index = distance / 25;

                        int resId = R.drawable.car_1;
                        switch (index) {
                            case 2:
                                resId = R.drawable.car_2;
                                break;
                            case 3:
                                resId = R.drawable.car_3;
                                break;
                            case 4:
                                resId = R.drawable.car_4;
                                break;
                            case 5:
                                resId = R.drawable.car_5;
                                break;
                            case 6:
                                resId = R.drawable.car_6;
                                break;
                            case 7:
                                resId = R.drawable.car_7;
                                break;
                            case 8:
                                resId = R.drawable.car_8;
                                break;
                            case 9:
                                resId = R.drawable.car_9;
                                break;
                            case 10:
                                resId = R.drawable.car_10;
                                break;
                        }
                        if (!isFreshEnable) {
                            carImage.setBackgroundResource(resId);
                        }

                    }

                    @Override
                    public void onPullEnable(boolean enable) {
                        isFreshEnable = enable;
                        if (enable) {
                            carImage.setBackgroundResource(R.color.colorTransparent);
                            carImage.setImageResource(R.drawable.car_frame);
                            mAnimation = (AnimationDrawable) carImage.getDrawable();
                        }
                    }
                });

    }

    private View createHeaderView() {
        View headerView = getLayoutInflater().inflate(R.layout.layout_head, null);
        carImage = (ImageView) headerView.findViewById(R.id.pb_view);
        return headerView;
    }

    @Override
    public void fetchData(int start, int pageSize) {
        mPresenter.fetchMore(mGoodsBarcode, start, pageSize);
    }

    @Override
    public BaseRvAdapter.SampleViewHolder createItemViewHolder(ViewGroup parent, int viewType) {
        View itemView = getLayoutInflater().inflate(R.layout.ordershow_item_list, null);
        return new OrderShowViewHolder(itemView);
    }

    @Override
    public void bindData(BaseRvAdapter.SampleViewHolder _holder, int position, Object _item) {
        final OrderShowViewHolder holder = (OrderShowViewHolder) _holder;
        final OrderShowItem item = (OrderShowItem) _item;
        String goodspic = item.userHeadImg;
        if (!TextUtils.isEmpty(goodspic)) {
            String[] split = goodspic.split(",");
            if (split.length > 0) {
                String picShow = split[0];
                Glide.with(getApplicationContext()).load(picShow).asBitmap()
                        .placeholder(R.drawable.avatar_default)
                        .diskCacheStrategy(DiskCacheStrategy.ALL).centerCrop()
                        .animate(R.anim.fade_in_image).into(holder.mCoverIv);
            }
        }else {
            holder.mCoverIv.setImageDrawable(getResources().getDrawable(R.drawable.avatar_default));
        }
        holder.mWinnerTv.setText(item.userName);
        holder.mTimeTv.setText(item.createTime);
        holder.mContentTv.setText(item.evaluateContent);
        String evaluatepic = item.evaluatePic;
        if (!TextUtils.isEmpty(evaluatepic)) {
            String[] split = evaluatepic.split(",");
            if (split.length > 0) {
                List<String> strings = Arrays.asList(split);
                PicGridListAdapter picGridListAdapter = new PicGridListAdapter(
                        OrderShowListActivity.this, strings, OrderShowListActivity.this);
                holder.mPicGridView.setAdapter(picGridListAdapter);
                picGridListAdapter.notifyDataSetChanged();
            }
        }

        holder.mRootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jump2OrderShowDetailPage(item.recordId);
            }
        });
    }

    @Override
    public void onPicItemClick(String picUrl) {
        if (TextUtils.isEmpty(picUrl)) {
            return;
        }
        jump2OriginalPicPage(picUrl);
    }

    class OrderShowViewHolder extends BaseRvAdapter.SampleViewHolder {
        @Bind(R.id.rootView)
        View mRootView;
        @Bind(R.id.iv_cover)
        CircleImageView mCoverIv;
        @Bind(R.id.tv_winner)
        TextView mWinnerTv;
        @Bind(R.id.tv_time)
        TextView mTimeTv;
        @Bind(R.id.tv_evaluatecontent)
        TextView mContentTv;
        @Bind(R.id.gridview)
        NoScrollGridView mPicGridView;

        public OrderShowViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}
